package com.todo.partner.application.frontend.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.todo.common.common.entity.response.BizPageResponse;
import com.todo.common.common.entity.response.BizResponse;
import com.todo.common.common.entity.response.page.PageResult;
import com.todo.common.common.enums.BizErrorCodeEnum;
import com.todo.common.common.exception.BizException;
import com.todo.partner.application.convert.PartnerConvert;
import com.todo.partner.application.entity.bo.PartnerContentDetailBO;
import com.todo.partner.application.entity.condition.ContentPartnerConditionBO;
import com.todo.partner.application.frontend.service.PartnerContentAggService;
import com.todo.partner.application.remote.UserInfoRemoteService;
import com.todo.partner.application.service.PartnerContentService;
import com.todo.partner.iface.frontend.request.*;
import com.todo.partner.iface.frontend.response.ContentPartnerBaseVO;
import com.todo.partner.iface.frontend.response.ContentPartnerDetailVO;
import com.todo.user.api.response.BaseUserInfoResponse;
import com.todo.user.api.response.BatchQuerySimplyUserInfoResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * (ContentPartner)表服务实现类
 *
 * @author zhangwenxiang
 * @since 2024-03-04 00:19:46
 */
@Slf4j
@Service("contentPartnerAggService")
public class PartnerContentAggServiceImpl implements PartnerContentAggService {

    @Resource
    private PartnerContentService partnerContentService;
    @Resource
    private UserInfoRemoteService userInfoRemoteService;


    @Override
    public BizResponse<Boolean> insertContentPartner(InsertContentPartnerParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        PartnerContentDetailBO partnerContentDetailBO = PartnerConvert.convertToPartnerContentDetailBO(param);
        Boolean insertResult = partnerContentService.insertContentPartner(partnerContentDetailBO);
        if (!insertResult) {
            log.error("ContentPartnerAggService#insertContentPartner 新增内容搭子完成，新增失败 入参：【{}】", JSONObject.toJSONString(param));
        }
        return BizResponse.success(insertResult);
    }

    @Override
    public BizResponse<Boolean> updateContentPartnerById(UpdateContentPartnerByIdParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }

        PartnerContentDetailBO partnerContentDetailBO = partnerContentService.queryContentPartner(Long.valueOf(param.getPartnerId()));
        if (partnerContentDetailBO == null || partnerContentDetailBO.getPartnerInfoBO() == null) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR, "保存失败，数据为空，请刷新后重试");
        }
        if (!partnerContentDetailBO.getPartnerInfoBO().getUserId().equals(param.get_user().getUserId())) {
            throw new BizException(BizErrorCodeEnum.ILLEGAL_OPERATION, "保存失败，您没有权限修改该内容");
        }
        PartnerContentDetailBO updatePartnerContentDetailBO = PartnerConvert.convertToUpdateContentPartnerRequest(param);
        Boolean updateResult = partnerContentService.updateContentPartner(updatePartnerContentDetailBO);
        if (!updateResult) {
            log.error("ContentPartnerAggService#updateContentPartnerById 更新内容搭子完成，更新失败 入参：【{}】", JSONObject.toJSONString(param));
        }
        return BizResponse.success(updateResult);
    }

    @Override
    public BizResponse<Boolean> removeContentPartnerById(RemoveContentPartnerByIdParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        PartnerContentDetailBO partnerContentDetailBO = partnerContentService.queryContentPartner(Long.valueOf(param.getPartnerId()));
        if (partnerContentDetailBO == null || partnerContentDetailBO.getPartnerInfoBO() == null) {
            return BizResponse.success(true);
        }
        if (!partnerContentDetailBO.getPartnerInfoBO().getUserId().equals(param.get_user().getUserId())) {
            throw new BizException(BizErrorCodeEnum.ILLEGAL_OPERATION, "删除失败，您没有权限修改该内容");
        }
        Boolean removeResult = partnerContentService.removeContentPartner(Long.valueOf(param.getPartnerId()));
        if (!removeResult) {
            log.error("ContentPartnerAggService#removeContentPartnerById 删除内容搭子完成，删除失败 入参：【{}】", JSONObject.toJSONString(param));
        }
        return BizResponse.success(removeResult);
    }

    @Override
    public BizResponse<ContentPartnerDetailVO> queryContentPartnerDetail(QueryContentPartnerDetailParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        BizResponse<BaseUserInfoResponse> userInfoResponse = userInfoRemoteService.queryBaseUserAccountInfoByUserId(param.get_user().getUserId());
        if (userInfoResponse == null || !userInfoResponse.isSuccess() || userInfoResponse.getData() == null) {
            log.warn("ContentPartnerAggService#queryContentPartnerDetail 查询搭子内容详情失败，用户数据不存在 入参：【{}】", JSONObject.toJSONString(param));
            return BizResponse.success();
        }
        BaseUserInfoResponse userInfo = userInfoResponse.getData();
        PartnerContentDetailBO partnerContentDetailBO = partnerContentService.queryContentPartner(Long.valueOf(param.getPartnerId()));
        if (partnerContentDetailBO == null) {
            log.warn("ContentPartnerAggService#queryContentPartnerDetail 查询搭子内容详情完成，数据为空 入参：【{}】", JSONObject.toJSONString(param));
            return BizResponse.success();
        }
        return BizResponse.success(PartnerConvert.buildContentPartnerDetailVO(partnerContentDetailBO, userInfo));
    }

    @Override
    public BizPageResponse<ContentPartnerBaseVO> queryContentPartnerByPage(QueryContentPartnerByPageParam param) {
        if (param == null || !param.baseCheck()) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        ContentPartnerConditionBO conditionBO = PartnerConvert.convertToContentPartnerConditionBO(param);
        PageResult<PartnerContentDetailBO> pageResult = partnerContentService.queryContentPartnerByCondition(conditionBO);
        if (pageResult == null) {
            return BizPageResponse.success();
        }
        if (CollectionUtils.isEmpty(pageResult.getResults())) {
            log.warn("ContentPartnerAggService#queryContentPartnerByPage 查询搭子内容详情完成，数据为空 入参：【{}】", JSONObject.toJSONString(param));
            return BizPageResponse.success(PageResult.of(null, pageResult.getPageNum(), pageResult.getPageSize(), pageResult.getTotal()));
        }
        Set<Long> userIdSet = pageResult.getResults().stream()
                .filter(item -> item != null && item.getPartnerInfoBO() != null)
                .map(item -> item.getPartnerInfoBO().getUserId()).collect(Collectors.toSet());
        BizResponse<BatchQuerySimplyUserInfoResponse> response = userInfoRemoteService.batchQuerySimplyUserInfo(new ArrayList<>(userIdSet));
        if (response == null || !response.isSuccess() || response.getData() == null) {
            log.warn("ContentPartnerAggService#queryContentPartnerByPage 查询搭子内容详情完成，用户数据不存在 userIdSet：【{}】", JSONObject.toJSONString(userIdSet));
            return BizPageResponse.success();
        }
        Map<Long, BatchQuerySimplyUserInfoResponse.SimplyUserInfo> simplyUserInfoMap = response.getData().getSimplyUserInfoMap();
        return BizPageResponse.success(PartnerConvert.buildContentPartnerDetailResponsePage(pageResult, simplyUserInfoMap));
    }
}
